<script setup>
  import { addBannerRcomApi, getArticleListApi, updateBannerRcomApi } from '@/api/article'
  import LvUpload from '@/components/LvUpload.vue'
  import useTable from '@/hooks/useTable'
  import { ElMessage } from 'element-plus'
  import { reactive, ref } from 'vue'

  const emit = defineEmits(['update'])

  const visible = ref(false)
  const { tableData, pager, pageChange } = useTable({ apiFn: getArticleListApi })
  const form = reactive({ _id: '', imageUrl: '', travel_id: '' })
  const pickData = ref([])
  const columnList = ref([
    { type: 'text', format: (row) => row.author_data[0].nickname, label: '作者', width: '120px' },
    { type: 'text', prop: 'time', label: '发布时间', width: '120px' },
    { type: 'text', format: (row) => row.city + '-' + row.address, label: '地址', width: '180px' },
    { type: 'text', prop: 'title', label: '标题' }
  ])

  // 选择游记
  const pickArticle = (row) => {
    form.travel_id = row._id
    pickData.value = [row]
  }

  // 提交数据
  const submitForm = async () => {
    // 1. 校验字段【封面上传、游记选择】
    if (!form.imageUrl) return ElMessage.error('请选择封面')
    if (!form.travel_id) return ElMessage.error('请关联游记')
    // 2. 提交数据【根据_id判断操作类型】
    form._id ? await updateBannerRcomApi(form) : await addBannerRcomApi(form)
    ElMessage.success('操作成功')
    emit('update')
    // 3. 关闭弹窗
    close()
  }

  const open = (row) => {
    if (row) {
      form._id = row._id
      form.imageUrl = row.imageUrl
      form.travel_id = row.travel_id
    }
    visible.value = true
  }

  const close = () => {
    visible.value = false
    form._id = ''
    form.imageUrl = ''
    form.travel_id = ''
    pickData.value = []
  }

  defineExpose({
    open,
    close
  })
</script>

<template>
  <!-- 选择推荐游记抽屉层 -->
  <el-drawer v-model="visible" size="50%" destroy-on-close :with-header="false">
    <!-- 封面区域 -->
    <div class="cover-view">
      <LvUpload v-model:imageUrl="form.imageUrl" />

      <el-button type="success" size="large" @click="submitForm">提交</el-button>
    </div>
    <!-- 已选择游记 -->
    <div class="pick-view" v-if="pickData.length">
      <div class="title">已选择游记</div>
      <LvTable :data="pickData" :columnList="columnList" />
    </div>
    <!-- 游记列表 -->
    <div class="list-view">
      <div class="title">请选择一个游记关联</div>
      <LvTable highlight :data="tableData" :columnList="columnList" @row-click="pickArticle" />
      <LvPagination :total="pager.total" :page="pager.page" @change="pageChange" />
    </div>
  </el-drawer>
</template>

<style scoped lang="scss">
  .cover-view {
    display: flex;
    justify-content: space-between;
    ::v-deep(.upload) {
      width: 200px;
      height: 200px;
    }
    .el-button {
      width: 120px;
    }
  }
  .pick-view,
  .list-view {
    padding-bottom: 10px;
    .title {
      font-size: 18px;
      font-weight: 700;
      padding: 20px 0;
    }
  }
</style>
